import React, { useState, useEffect, useRef } from 'react';
import { DropDownBox } from 'devextreme-react/drop-down-box';
import { List } from 'devextreme-react/list';
import TreeView from 'devextreme-react/tree-view';
import Button from 'devextreme-react/button';
import ErrorBounced from '@/pages/components/ErrorBounced';
import { formatterTime, intl } from '@/utils';
import getApiData from '@/services/cpasRequest';
import { ScrollView } from 'devextreme-react/scroll-view';
import { useModel } from 'umi';
import notify from 'devextreme/ui/notify';
import axios from 'axios';
import dxList from 'devextreme/ui/list';
import SelectBox from 'devextreme-react/select-box';
import ErrorBouncedChangeName from '@/pages/components/ErrorBounced/errorBouncedChangeName';
import { deepClone } from "~/public/cpas-business/tools/Tools";
const YearlyAuditPaperForm = ({ fetchData, setShowYearlyAuditPaper, showYearlyAuditPaper }: any) => {
  const { initialState } = useModel('@@initialState');
  const { dbname, zcbfid, sjxmbh, sjnd } = initialState?.curPart as API.CurPart;
  const { username, usercode } = initialState?.curUser as API.CurPart;

  // const tplDialogRef = useRef<any>();
  const [valueOptions, setValueOptions] = useState<any>('');
  const [selectedYears, setSelectedYears] = useState<any>('');
  const [selectedPaper, setSelectedPaper] = useState<Object>({});
  const [sourceList, setSourceList] = useState<any[]>([]);
  const [paperList, setPaperList] = useState<any[]>([]);
  const [selectedPaperList, setSelectedPaperList] = useState<{ phase: any[]; paper: any[] }>({
    phase: [],
    paper: [],
  });
  // const [Time, setTime] = useState([])
  const yearPeriod = getYearPeriod();

  const [yearPeriodNd, setYearPeriodNd] = useState<any>(0);

  const paperTreeViewRef = useRef<TreeView>(null);
  const TreeViewRef = useRef<any>();
  const DownBoxRef = useRef<any>();
  const errorBouncedRefChangeNameRef = useRef<any>();
  // const tplDialogErrorRef = useRef<any>();


  async function sourceListRefresh() {
    const sList = await getSourceList();
    setSourceList(sList);
  }

  async function paperListRefresh() {
    const pList = await getPaperList(selectedPaper);
    setPaperList(pList);
  }

  useEffect(() => {
    sourceListRefresh();
    setYearPeriodNd(Number(sjnd));
    setSelectedYears(Number(sjnd));

    // 获取当前年度
    // let time = new Date()
    // let times = formatterTime(time)
    // let currentTime: any = times.split('-')[0]
    // yearPeriod.map((item: any) => {
    //   if (item.toString() === currentTime) {
    //     setTime(item);
    //   }
    // })
  }, []);

  useEffect(() => {
    if (showYearlyAuditPaper) {
      setSelectedPaper('');
      setPaperList([]);
      setYearPeriodNd(Number(sjnd));
      setSelectedYears(Number(sjnd));
      TreeViewRef.current.instance.unselectAll();
      setValueOptions('');
    }
  }, [showYearlyAuditPaper]);



  useEffect(() => {
    paperListRefresh();
  }, [selectedPaper]);

  function setDisabled(allSelected: any[], paperList: any[]) {
    const tempPaperList: any[] = [];
    for (let i = 0; i < paperList.length; i++) {
      tempPaperList.push(paperList[i]);
      tempPaperList[i].disabled = false;
    }
    for (let i = 0; i < tempPaperList.length; i++) {
      for (let j = 0; j < allSelected.length; j++) {
        if (
          paperList[i].dgmc === allSelected[j].itemData.dgmc &&
          paperList[i].id !== allSelected[j].itemData.id
        ) {
          tempPaperList[i].disabled = true;
        }
      }
    }
    setPaperList(tempPaperList);
  }



  // const getRelatedNodes = (node, nodes = []) => {
  //   if (node) {
  //     nodes.unshift(node);
  //     const parentNode = paperTreeViewRef.current?.instance?.getParentNode(node);
  //     // paperTreeViewRef.current?.instance.getSelectedNodes();

  //     if (parentNode) {
  //       getRelatedNodes(parentNode, nodes);
  //     }
  //   }
  //   return nodes;
  // };

  // const funcBBB = (funData: any) => {
  //   let aaaa: any = [];
  //   funData?.forEach((item: any) => {
  //     if (item.parent) {
  //       const resss = aaaa.some((items: any) => items.key === item.parent.key);
  //       if (!resss) {
  //         aaaa.push(item.parent);
  //       }
  //     }
  //   });
  //   console.log(aaaa, '@@@ funcBBB');
  //   funcBBB(aaaa);
  //   return aaaa;
  // }



  // function findNodesToTopLevel(selectedNode) {
  //   const nodesToTopLevel = [];

  //   function traverse(node) {
  //     if (node) {
  //       nodesToTopLevel.push(node);
  //       const parentNode = node.parent;
  //       traverse(parentNode);
  //     }
  //   }

  //   traverse(selectedNode);
  //   return nodesToTopLevel;
  // }

  /**
   * 支持获取半选状态父节点
   */
  function getAllParentByNotes(notesData: any) {
    // dev 不支持获取半选状态下的多选状态
    const pNodeSet = new Set();
    const leafNodeSet = new Set();
    const leafDgSyhNodeSet = new Set();

    function deepNodes(nodes: any) {
      for (let i = 0; i < nodes.length; i++) {
        const note = nodes[i];
        if (note.parent) {
          pNodeSet.add(note.parent.key)
          if (note.children.length === 0) {
            leafNodeSet.add(note.key);
            leafDgSyhNodeSet.add(note.itemData.dgSyh);
          }
          deepNodes([note.parent]);
        } else if (note.children.length === 0) {
          leafNodeSet.add(note.key);
          leafDgSyhNodeSet.add(note.itemData.dgSyh);
        }
      }
    }
    deepNodes(notesData);
    return {
      parentNode: Array.from(pNodeSet),
      leafNode: Array.from(leafNodeSet),
      leafDgSyhNode: Array.from(leafDgSyhNodeSet)
    };
  }



  return (
    <>
      <div style={{ display: 'flex', }}>
        <p style={{ margin: ' 4pt 4pt 0pt 0', marginRight: '10pt' }}>{intl('audit.select', '选择底稿年度:')}</p>
        {/* <span onClick={()=>{
        TreeViewRef.current.instance.collapseAll();
      }}>点击</span> */}
        {/* 默认 当前年度 */}
        <SelectBox
          items={yearPeriod}
          width={200}
          height={32}
          defaultValue={yearPeriodNd}
          value={yearPeriodNd}
          searchEnabled={true}
          onSelectionChanged={(e: any) => {
            setYearPeriodNd(e.selectedItem);
            setSelectedYears(e.selectedItem);
          }}
        />
        <p style={{ marginTop: '4pt', marginLeft: '15pt', marginRight: '10pt' }}>
          {intl('audit.source', '选择底稿来源:')}
        </p>
        <DropDownBox
          ref={DownBoxRef}
          value={selectedPaper}
          width={340}
          height={32}
          displayExpr="text"
          valueExpr="value"
          placeholder={selectedPaper.viewName}
          deferRendering={false}
          showClearButton={true}
        >
          <TreeView
            ref={TreeViewRef}
            className='DropDownBoxTreeView'
            dataSource={sourceList}
            dataStructure="plain"
            keyExpr="id"
            parentIdExpr="pid"
            displayExpr="viewName"
            selectionMode="single"
            selectByClick={true}
            onItemSelectionChanged={(e: any) => {
              DownBoxRef.current.instance.close();
              TreeViewRef.current.instance.collapseAll();
              if (e.itemData.pid !== null) {
                if (e.itemData.selected) {
                  setSelectedPaper(e.itemData);
                } else {
                  setSelectedPaper({});
                }
              }
            }}
          />
        </DropDownBox>
      </div>

      {/* 底稿选择 */}

      <div style={{ display: 'block', justifyContent: 'center', height: '80%' }}>
        <h4 style={{ marginRight: '30px', fontSize: '16px' }}>底稿名称</h4>
        {/* <ScrollView scrollByThumb={true} direction="vertical" height="100%"> */}
        <TreeView
          className='NewTreeView'
          dataSource={paperList}
          dataStructure="plain"
          keyExpr="id"
          parentIdExpr="pid"
          displayExpr="viewName"
          selectionMode="multiple"
          selectByClick={true}
          showCheckBoxesMode="selectAll"
          ref={paperTreeViewRef}
          disabledExpr="disabled"
          searchEnabled={true}
          searchMode={'contains'}
          selectNodesRecursive={true}
        // onSelectionChanged={(e) => {
        // console.log(e, '@@@');

        // getRelatedNodes(e.id);
        // const tempPhase: any[] = [];
        // const tempPaper: any[] = [];

        // const arr: any = []
        // allSelected?.map((item: any) => {
        //   if (item) {
        //     arr.push(item)
        //   } else {
        //     return [];
        //   }
        // })

        // if (arr) {
        //   for (let i = 0; i < arr.length; i++) {
        //     if (arr[i].itemData.pid !== null) {
        //       tempPaper.push(arr[i].itemData.id);
        //       tempPhase.push(arr[i].itemData.pid);
        //     }
        //   }
        // }
        // setSelectedPaperList({
        //   phase: tempPhase,
        //   paper: tempPaper,
        // });
        // // 把选项disable
        // setDisabled(arr, paperList);
        // }}
        />
        {/* </ScrollView> */}
      </div>

      {/* 确定按钮 */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'right',
          alignItems: 'center',
          // position: 'absolute',
          // bottom: '10px',
          // right: '20px',
          width: '100%',
          height: '50px',
          borderTop: '2px solid #ccc',
          marginTop: '30px'
        }}
      >
        <Button
          text={intl('audit.cancel', '取消')}
          width={88}
          onClick={async () => {
            setShowYearlyAuditPaper(false);
            setSelectedPaper('');
            setPaperList([]);
            setYearPeriodNd(Number(sjnd));
            TreeViewRef.current.instance.unselectAll();
          }}
        />
        <Button
          type='default'
          text={intl('audit.ok', '确定')}
          width={88}
          onClick={() => {


            const allSelected = paperTreeViewRef.current?.instance.getSelectedNodes();

            const selectResult = getAllParentByNotes(allSelected);

            const { leafNode } = selectResult;

            if (selectedYears.length === 0 || leafNode.length === 0) {
              notify(intl('audit.yearly.selectError', '请先选择选项'), 'error', 1000);
              return;
            }
            createYearlyPaper(
              selectedYears,
              selectedPaper,
              dbname,
              zcbfid,
              selectResult,
              username,
              sjxmbh,
            ).then(r => {
              console.log(r, selectResult, 'r---');
              const { data } = r;

              if (data.length === 0) {
                notify('添加成功', 'success', 1000);
                fetchData();
                setShowYearlyAuditPaper(false);
                setSelectedPaper('');
                setPaperList([]);
                setYearPeriodNd(Number(sjnd));
                TreeViewRef.current.instance.unselectAll();
              } else {
                let tempselectResult: any = deepClone(selectResult);
                // 错误弹窗
                errorBouncedRefChangeNameRef.current.show({
                  args: {
                    codes: true,
                    dbname,
                    dgnd: selectedYears,
                    pupopType: 'dg',
                    data: data,
                    valueSource: 'payload'
                  },
                  okCallback: (tempData: any[]) => {
                    // console.log(tempData, '@@@ okCallback');
                    if (tempData.length > 0) {
                      let changeResult: any = {
                        // parentNode: tempselectResult?.parentNode,
                        rleafNode: tempData[0],
                        rleafDgSyhNode: tempData[1]
                      }
                      createYearlyPaper(
                        selectedYears,
                        selectedPaper,
                        dbname,
                        zcbfid,
                        tempselectResult,
                        username,
                        sjxmbh,
                        changeResult,
                      ).then((res) => {
                        if (res.ok) {
                          fetchData();
                          setShowYearlyAuditPaper(false);
                          setSelectedPaper('');
                          setPaperList([]);
                          setYearPeriodNd(Number(sjnd));
                          TreeViewRef.current.instance.unselectAll();
                        } else {
                          notify('导入失败', 'error', 3000);
                        }
                      });

                    } else {
                      fetchData();
                      setShowYearlyAuditPaper(false);
                      setSelectedPaper('');
                      setPaperList([]);
                      setYearPeriodNd(Number(sjnd));
                      TreeViewRef.current.instance.unselectAll();
                    }
                  },
                  cancelCallback: () => {
                    fetchData();
                    setShowYearlyAuditPaper(false);
                    TreeViewRef.current.instance.unselectAll();
                  }
                });
              }
            })
          }}
        />
      </div>
      {/* <ErrorBounced ref={tplDialogErrorRef} /> */}
      <ErrorBouncedChangeName ref={errorBouncedRefChangeNameRef} />
    </>
  );
};

const getYearPeriod = (): number[] => {
  const date = new Date();
  const year = date.getFullYear();
  const years: any = [];
  for (let i = 1; i < 6; i++) {
    years.push(year - i);
    years.push(year + i);
  }
  years.push(year);
  years.sort((a, b) => a - b);
  return years;
};

async function getSourceList(): Promise<any[]> {
  const res = await getApiData('wp.tplSource');
  if (res.ok) {
    return res.data;
  } else {
    return [];
  }
}

async function getPaperList(selectedPaper: any) {
  if (selectedPaper.pid === '1') {
    const res = await getApiData('wp.tplTree', {
      dbname: selectedPaper.id,
    });
    if (res.ok) {
      for (let i = 0; i < res.data.length; i++) {
        if (
          res.data[i].dglx === '.' ||
          res.data[i].dglx === '..' ||
          res.data[i].dglx === 'nd'
        ) {
          res.data[i].viewName = res.data[i].dgmc;
        } else {
          res.data[i].viewName = res.data[i].dgmc + res.data[i].dglx;
        }
      }
      console.log(res.data);
      return res.data;
    } else {
      return [];
    }
  } else if (selectedPaper.pid === '2') {
    const res = await getApiData('wp.tplTree', {
      tplName: selectedPaper.id,
    });
    if (res.ok) {
      for (let i = 0; i < res.data.length; i++) {
        if (
          res.data[i].dglx === '.' ||
          res.data[i].dglx === '..' ||
          res.data[i].dglx === 'nd'
        ) {
          res.data[i].viewName = res.data[i].dgmc;
        } else {
          res.data[i].viewName = res.data[i].dgmc + res.data[i].dglx;
        }
      }
      return res.data;
    } else {
      return [];
    }
  }
}

async function createYearlyPaper(
  selectedYears: string | any[],
  selectedPaper: any,
  dbname: string,
  zcbfid: string,
  selectResult: any,
  username: any,
  sjxmbh: any,
  rSelectResult: any = null,
) {
  const { parentNode, leafNode, leafDgSyhNode } = selectResult;
  let paramsObj: any = {
    dgnd: selectedYears,
    type: selectedPaper.fPath === null ? '0' : '1',
    sourcePath: selectedPaper.fPath === null ? selectedPaper.id : selectedPaper.fPath,
    distPath: `${sjxmbh}/${zcbfid}`,
    sjjds: parentNode,
    sjdgs: leafNode,
    dgsyhs: leafDgSyhNode,
    user: username,
    dbname: dbname,
  }

  if (rSelectResult) {
    const { rleafNode, rleafDgSyhNode } = rSelectResult;
    paramsObj = {
      ...paramsObj,
      rdgmcs: rleafNode,
      rdgsyh: rleafDgSyhNode
    }
  }
  // 接口
  const res = await axios.post('/cpasApi/draftManage/createDgByYear', paramsObj);
  return res.data
}


export default YearlyAuditPaperForm;
